#include "file_helper.h"

namespace autodrive {
namespace perception {
std::string read_text(std::filesystem::path const& path) noexcept(false) {
  if (!std::filesystem::exists(path)) {
    throw std::runtime_error(path.string() + " does not exist");
  }
  std::fstream stream{path, stream.in};
  if (!stream.good() || !stream.is_open()) {
    throw std::runtime_error("fail to open file " + path.string());
  }

  try {
    std::stringstream s;
    s << stream.rdbuf();
    stream.close();
    return s.str();
  } catch (const std::exception& e) {
    stream.close();
    throw std::runtime_error(path.string() + " read error, " + e.what());
  } catch (...) {
    stream.close();
    throw std::runtime_error(path.string() + " read error, unexpected");
  }
}
}  // namespace perception
}  // namespace autodrive